import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../controllers/auth_controller.dart';
import '../app_routes.dart';
import '../../services/storage/local_storage_service.dart';
import '../../constants/app_constants.dart';

/// 认证中间件 - 用于保护需要登录才能访问的路由
class AuthMiddleware extends GetMiddleware {
  final LocalStorageService _storageService = Get.find<LocalStorageService>();
  final AuthController _authController = Get.find<AuthController>();

  @override
  int? get priority => 2;

  @override
  RouteSettings? redirect(String? route) {
    // 检查是否已登录
    final isLoggedIn = _authController.isLoggedIn;
    
    // 如果访问的是登录相关页面，但已经登录了，则重定向到首页
    if (isAuthRoute(route) && isLoggedIn) {
      return const RouteSettings(name: AppRoutes.home);
    }
    
    // 如果访问的不是登录相关页面，且未登录，则重定向到登录页
    if (!isAuthRoute(route) && !isLoggedIn) {
      // 保存尝试访问的路由，登录后可以重定向回去
      if (route != null && route != AppRoutes.splash) {
        _storageService.write(AppConstants.tokenKey, route);
      }
      return const RouteSettings(name: AppRoutes.login);
    }
    
    // 正常情况下不重定向
    return null;
  }
  
  /// 判断是否为认证相关路由（无需登录即可访问的页面）
  bool isAuthRoute(String? route) {
    return route == AppRoutes.splash ||
           route == AppRoutes.onboarding ||
           route == AppRoutes.login ||
           route == AppRoutes.register ||
           route == AppRoutes.forgotPassword ||
           route == AppRoutes.resetPassword;
  }
  
  @override
  GetPage? onPageCalled(GetPage? page) {
    return page;
  }
  
  @override
  List<Bindings>? onBindingsStart(List<Bindings>? bindings) {
    return bindings;
  }
  
  @override
  GetPageBuilder? onPageBuildStart(GetPageBuilder? page) {
    debugPrint('页面构建中: ${page.toString()}');
    return page;
  }
  
  @override
  Widget onPageBuilt(Widget page) {
    debugPrint('页面已构建: ${page.runtimeType}');
    return page;
  }
  
  @override
  void onPageDispose() {
    debugPrint('页面已释放');
  }
} 